package com.imooc.ad.service.impl;

import com.imooc.ad.constant.Constants;
import com.imooc.ad.dao.AdUserRepository;
import com.imooc.ad.entity.AdUser;
import com.imooc.ad.exception.AdException;
import com.imooc.ad.service.IUserService;
import com.imooc.ad.utils.CommonUtils;
import com.imooc.ad.vo.CreateUserRequest;
import com.imooc.ad.vo.CreateUserResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

/*
 * @author Qihs
 */
@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    private  final AdUserRepository userRepository;

    @Autowired
    public  UserServiceImpl(AdUserRepository userRepository){
        this.userRepository = userRepository;
    }

    @Override
    @Transactional //开启事务
    public CreateUserResponse createUser(CreateUserRequest request) throws AdException {
        //验证传入的参数是否正确
        if (!request.validate()){
            throw new AdException(Constants.ErrorMsg.REQUEST_PARAM_ERROR);
        }
        //验证是否有同名用户
        AdUser oldUser = userRepository.findByUsername(request.getUsername());
        if (oldUser !=null){
            throw new AdException(Constants.ErrorMsg.SAME_PARAM_ERROR);
        }
        /**
         * 创建用户，AdUser只需要username与token两个参数
         * 用户输入的username验证通过后，通过对username进行MD5，得出token值
         * 获得请求的用户名request.getUsername()，与获得token的值CommonUtils.md5(request.getUsername())
         */
        AdUser newUser = userRepository.save(new AdUser(request.getUsername(), CommonUtils.md5(request.getUsername())));
        //填充Response，并返回数据
        return new CreateUserResponse(newUser.getId(), newUser.getUsername(),
                newUser.getToken(), newUser.getCreatTime(), newUser.getUpdateTime());
    }
}
